<template>
  <div class="page-container fixed-bottom">
    <template v-if="status === 1 || status=== 2">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="列表封面：" prop="coverImg">
          <UploadFile :file-list="form.coverImg" @change="uploadHandle($event, 'coverImg','coverImg')">
            <div slot="tip">封面690*350px，小于1M的JPG/PNG/GIF格式的图片</div>
          </UploadFile>
        </el-form-item>
        <el-form-item label="景区开放时间：" prop="openTime">
          <div v-for="(item,dateIndex) in form.timeRules" :key="dateIndex">
            <div class="data-list-box">
              <div class="data-box">
                <el-date-picker
                  v-model="item.dateRange"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </div>
              <div v-for="(timeItem,timeIndex) in item.timeList" :key="timeIndex" class="time-list-box clearfix">
                <el-col class="time-item" :span="4">
                  <el-select v-model="timeItem.weekValue">
                    <el-option :value="1" label="周一" />
                    <el-option :value="2" label="周二" />
                    <el-option :value="3" label="周三" />
                    <el-option :value="4" label="周四" />
                    <el-option :value="5" label="周五" />
                    <el-option :value="6" label="周六" />
                    <el-option :value="7" label="周日" />
                    <el-option :value="8" label="周一到周五" />
                    <el-option :value="9" label="全部时间" />
                  </el-select>
                </el-col>
                <el-col class="time-item" :span="4">
                  <el-select v-model="timeItem.dayType1" @change="changeDayType($event, dateIndex, timeIndex)">
                    <el-option :value="1" label="上午" />
                    <el-option :value="2" label="全天" />
                  </el-select>
                </el-col>
                <el-col class="time-item" :span="5">
                  <el-time-picker
                    v-model="timeItem.amTimeRange"
                    is-range
                    value-format="HH:mm"
                    format="HH:mm"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                  />
                </el-col>
                <el-col class="time-item" :span="4">
                  <el-select v-model="timeItem.dayType2" :disabled="timeItem.dayType1 === 2">
                    <el-option :value="2" label="下午" />
                  </el-select>
                </el-col>
                <el-col class="time-item" :span="5">
                  <el-time-picker
                    v-model="timeItem.pmTimeRange"
                    is-range
                    value-format="HH:mm"
                    format="HH:mm"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :disabled="timeItem.dayType1 === 2"
                  />
                </el-col>
                <el-col class="time-item" :span="2">
                  <el-button v-if="timeIndex === 0" icon="el-icon-plus" @click="addTimeItem(dateIndex)" />
                  <el-button v-else icon="el-icon-minus" @click="deleteTimeItem(dateIndex, timeIndex)" />
                </el-col>
              </div>
            </div>
            <p class="add-box">
              <el-button v-if="dateIndex === 0" @click="addDateItem">添加时段</el-button>
              <el-button v-else @click="deleteDateItem(dateIndex)">删除时段</el-button>
            </p>
          </div>
        </el-form-item>
        <el-form-item label="是否需要门票：" required>
          <el-switch v-model="form.isNeed" active-text="是" inactive-text="否" :inactive-value="0" :active-value="1" />
        </el-form-item>
        <el-form-item label="商家相册：" prop="shopAlbum">
          <UploadFile :file-list="form.albumImgUrls" :limit="9" @change="uploadHandle($event, 'albumImgUrls','shopAlbum')">
            <div slot="tip">建议尺寸：封面690*350px，首图/详情图690*350px，小于1M的JPG/PNG/GIF格式的图片。最多上传9张图片</div>
          </UploadFile>
          <UploadFile :file-list="form.albumVideoUrls" file-type="file" accept=".mp4" :limit="3" @change="uploadHandle($event, 'albumVideoUrls', 'shopAlbum')">
            <div slot="tip">小于100M的视频格式文件。最多上传3个</div>
          </UploadFile>
        </el-form-item>
        <el-form-item label="简介/攻略：" prop="description">
          <RichText :value.sync="form.description" />
        </el-form-item>
      </el-form>
      <div class="bottom-handle-box">
        <el-button v-if="!id" @click="confirmHandle(true)">保存草稿</el-button>
        <el-button type="primary" @click="confirmHandle(false)">发布</el-button>
      </div>
    </template>
    <Result
      v-if="status === -1 || status=== 0"
      :type="'shop'"
      :status="status"
      @reason="showReason"
      @cancel="cancelHandle"
      @resubmit="reSubmit"
    />
    <Reject
      v-if="showReject"
      :reject-form="rejectForm"
      @close="closeHandle"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import UploadFile from '@/components/UploadFile/index.vue'
import RichText from '@/components/RichText/index.vue'
import Result from '@/components/Approve/Result.vue'
import Reject from '@/components/Approve/Reject.vue'
import { getShopDraft, decorationShop } from '@/api/shop'
import { rollShopBack, getLatestShop } from '@/api/common'
export default {
  name: 'ShopFace',
  components: {
    UploadFile,
    RichText,
    Result,
    Reject
  },
  data() {
    const validateShopAlbum = (rule, value, callback) => {
      if (this.form.albumImgUrls || this.form.albumVideoUrls) {
        callback()
      } else {
        callback(new Error('请上传商家相册'))
      }
    }
    const validateBusinessTime = (rule, value, callback) => {
      let flag = true
      this.form.timeRules.map(item => {
        if (!item.dateRange) {
          flag = false
        }
        item.timeList.map(timeItem => {
          if (!((timeItem.weekValue && timeItem.dayType1 && timeItem.amTimeRange) || (timeItem.weekValue && timeItem.dayType2 && timeItem.pmTimeRange))) {
            flag = false
          }
        })
      })
      if (flag) {
        callback()
      } else {
        callback(new Error('请输入景区开放时间'))
      }
    }
    return {
      id: '', // 门店id
      status: '', // 审核状态  -1：待审核  0：未通过 1：已通过  2：已撤销
      showReject: false,
      rejectForm: {},
      form: {
        coverImg: '',
        timeRules: [{
          dateRange: '',
          timeList: [
            {
              amTimeRange: null,
              dayType1: '',
              dayType2: '',
              pmTimeRange: null,
              weekValue: ''
            }
          ]
        }],
        isNeed: 0,
        albumImgUrls: '',
        albumVideoUrls: '',
        description: ''
      },
      rules: {
        coverImg: [{ required: true, message: '请上传列表封面', trigger: ['blur'] }],
        openTime: [{ required: true, validator: validateBusinessTime, message: '请输入景区开放时间', trigger: ['change'] }],
        shopAlbum: [{ required: true, validator: validateShopAlbum, trigger: ['change'] }],
        description: [{ required: true, message: '请输入门店详情', trigger: ['change'] }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'currentEnterprise',
      'currentSite'
    ])
  },

  created() {
    this.getLatest()
  },

  methods: {

    // 获取最近审核记录
    getLatest() {
      const data = {
        siteId: this.currentSite.id
      }
      getLatestShop(data).then(res => {
        const { id, approveStatus, rejectReason, rejectFileUrl } = res
        if (id) {
          // 有审核记录时
          this.status = approveStatus
          this.rejectForm = {
            rejectReason,
            rejectFileUrl
          }
          this.getShopDraft()
        } else {
          this.status = 1
        }
      }).catch(() => {})
    },

    // 获取店铺装修草稿
    getShopDraft() {
      const data = {
        siteId: this.currentSite.id
      }
      getShopDraft(data).then(res => {
        if (res.id) {
          const { id, coverImg, timeRules, isNeed, albumImgUrls, albumVideoUrls, description } = res
          this.id = id
          const dateList = (timeRules || []).map(item => {
            const timeList = item.timeRuleBaseVOS.map(timeItem => {
              let dayType1 = ''
              if (timeItem.type1 === 1) {
                dayType1 = 1
              } else if (timeItem.dayRule === 1) {
                dayType1 = 2
              }
              return {
                amTimeRange: [timeItem.amStartTime || '', timeItem.amEndTime || ''],
                dayType1: dayType1 || '',
                dayType2: timeItem.type2 || '',
                pmTimeRange: [timeItem.pmStartTime || '', timeItem.pmEndTime || ''],
                weekValue: timeItem.weekValue || ''
              }
            })
            return {
              dateRange: [item.startDate || '', item.endDate || ''],
              timeList
            }
          })
          this.form = {
            coverImg,
            timeRules: dateList?.length ? dateList : this.form.timeRules,
            isNeed,
            albumImgUrls,
            albumVideoUrls,
            description
          }
        }
      }).catch(() => {})
    },

    changeDayType(value, dateIndex, timeIndex) {
      if (value === 2) {
        this.form.timeRules[dateIndex].timeList[timeIndex].dayType2 = ''
        this.form.timeRules[dateIndex].timeList[timeIndex].pmTimeRange = null
      }
    },

    // 新增
    addTimeItem(dateIndex) {
      const item = {
        amTimeRange: null,
        dayType1: '',
        dayType2: '',
        pmTimeRange: null,
        weekValue: ''
      }
      this.form.timeRules[dateIndex].timeList.push(item)
    },

    // 删除
    deleteTimeItem(dateIndex, timeIndex) {
      this.form.timeRules[dateIndex].timeList.splice(timeIndex, 1)
    },

    // 新增
    addDateItem() {
      const item = {
        dateRange: '',
        timeList: [
          {
            amTimeRange: null,
            dayType1: '',
            dayType2: '',
            pmTimeRange: null,
            weekValue: ''
          }
        ]
      }
      this.form.timeRules.push(item)
    },

    // 删除
    deleteDateItem(dateIndex) {
      this.form.timeRules.splice(dateIndex, 1)
    },

    // 保存
    async confirmHandle(draft) {
      if (!draft) {
        await this.$refs.form.validate()
      }

      const timeRules = this.form.timeRules.map(item => {
        const timeRuleBaseVOS = item.timeList.map(timeItem => {
          return {
            weekValue: timeItem.weekValue,
            dayRule: (timeItem.dayType1 === 2 || (timeItem.dayType1 && timeItem.dayType2)) ? 1 : 0,
            type1: timeItem.dayType1 === 1 ? 1 : undefined,
            type2: timeItem.dayType2 === 2 ? 2 : undefined,
            amStartTime: timeItem.dayType1 ? timeItem.amTimeRange[0] : undefined,
            amEndTime: timeItem.dayType1 ? timeItem.amTimeRange[1] : undefined,
            pmStartTime: timeItem.dayType2 ? timeItem.pmTimeRange[0] : undefined,
            pmEndTime: timeItem.dayType2 ? timeItem.pmTimeRange[1] : undefined
          }
        })
        return {
          startDate: item.dateRange[0],
          endDate: item.dateRange[1],
          timeRuleBaseVOS
        }
      })

      const data = {
        ...this.form,
        timeRules,
        draft,
        enterpriseId: this.currentEnterprise.id,
        siteId: this.currentSite.id,
        id: this.id ? this.id : undefined
      }
      decorationShop(data).then(() => {
        if (draft) {
          this.$message.success('保存草稿成功')
        } else {
          this.$message.success('发布成功')
          this.status = -1
        }
      }).catch(() => {})
    },

    // 撤销发布
    cancelHandle() {
      const data = {
        siteId: this.currentSite.id
      }
      this.$confirm('确定要撤销发布吗?', '提示', {
        type: 'warning'
      }).then(() => {
        rollShopBack(data).then(() => {
          this.$message.success('撤销发布成功')
          this.getLatest()
        }).catch(() => {})
      }).catch(() => {})
    },

    // 展示拒绝原因
    showReason() {
      this.showReject = true
    },

    // 关闭
    closeHandle() {
      this.showReject = false
    },

    // 重新提交
    reSubmit() {
      this.status = 1
    },

    // 上传图片处理
    uploadHandle(payload, name, prop) {
      const fileList = payload.fileList
      const result = []
      fileList.map(item => {
        result.push(item.url)
      })
      this.form[name] = result.join(',')
      this.$refs.form.validateField(prop)
    }

  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.data-list-box{
  border: 1px solid #ebeef5;
  margin-bottom: 20px; width: 100%;
  .data-box{
    text-align: left;
    padding: 20px;
    width: 400px;
  }
  .time-list-box{
    text-align: left;
    border-top: 1px solid #ebeef5;
  }
  .time-item{
    border-right: 1px solid #ebeef5;
    padding: 20px;
    &:last-child{
      border-right: none
    }
  }
  .el-range-editor{
    width: 100%;
  }
}

.add-box{
  margin-bottom: 20px;
}

</style>
